package com.gmrz.uap.model;

import com.gmrz.uap.cfg.SystemConst;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Iterator;
import java.util.Map;

public class PluginArgument extends Model<PluginArgument> {
    private static final Logger LOG = LogManager.getLogger(PluginArgument.class);
    public static final PluginArgument dao = new PluginArgument();

    private static final String NAMESPACE = "servicePlugin";
    private static final String SQL_SELECT_COMM = NAMESPACE + SystemConst._DEFAULT_SEPARATOR_DOT + "select_comm";

    /**
     * 根据页面传过来的条件进行分页查询
     *
     * @param pluginArgument 白名单信息
     * @param page           页号
     * @param rows           行数
     * @param sort           排序字段
     * @param order          升序/降序
     * @return　分页结果 Page<WhiteList>
     */
    public Page<PluginArgument> findListForPaginate(PluginArgument pluginArgument, int page, int rows, String sort, String order, String tenantid) {

        StringBuilder sql = new StringBuilder();

        sql.append("from t_plugin_argument where pa_id=pa_id ");

        Iterator i = pluginArgument._getAttrsEntrySet().iterator();

        //循环遍历传过来的参数，并将参数拼接到SQL
        while (i.hasNext()) {
            Map.Entry<String, Object> obj = (Map.Entry<String, Object>) i.next();

            if (StrKit.isBlank(obj.getKey())) continue;

            if (StringUtils.equalsIgnoreCase("pa_id", obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = " + obj.getValue());
                continue;
            }

            //如果数据为空或为NULL的时候，跳过此次循环进入下一次循环
            if (null == obj.getValue() || "" == obj.getValue()) {
                continue;
            }
            sql.append(" and " + obj.getKey() + " like '%" + obj.getValue() + "%'");

        }

        sql.append(" order by " + sort + " " + order);

        return this.paginate(page, rows, getSql(SQL_SELECT_COMM), sql.toString());
    }

    public PluginArgument findByName(String configName) {
        StringBuilder sql = new StringBuilder();
        sql.append("select * from t_plugin_argument where config_cname = ?");
        return this.findFirst(sql.toString(), configName);
    }


    public PluginArgument findByServicePluginId(String servicePluginId) {
        StringBuilder sql = new StringBuilder();
        sql.append("select * from t_plugin_argument where sp_id = ?");
        return this.findFirst(sql.toString(), servicePluginId);
    }

}
